package Socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.HashMap;
import java.util.Map;

/**
 * 英译汉本地小程序
 * @author 徐梦轲
 * @create 2022-06-25 13:45
 */
public class Server {
    private DatagramSocket socket = null;
    private HashMap<String, String> dict = new HashMap<>();
    public Server(int port) throws SocketException {
        this.socket = new DatagramSocket(port);
        dict.put("hello","你好");
        dict.put("cat","小猫");
        dict.put("dog","小狗");
    }

    public void start() throws IOException {
        System.out.println("服务器启动!!!");
        //读取请求
        while (true) {
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(requestPacket);
            //解析请求
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            //计算响应
            String response = process(request);
            //发送响应给客户端
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),0,response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePacket);
            //打印日志
            String log = String.format("[ %s : %d ] request: %s response: %s",requestPacket.getAddress(),
                    requestPacket.getPort(),request,response);
            System.out.println(log);

        }
    }
    private String process(String request) {
        return dict.getOrDefault(request,"[单词在词典中不存在]");
    }

    public static void main(String[] args) throws IOException {
        Server server = new Server(9090);
        server.start();
    }
}
